import { writable, derived } from 'svelte/store';
import en from '../i18n/locales/en';
import zh from '../i18n/locales/zh';

// 支持的语言
export const languages = {
  zh: '中文',
  en: 'English',
} as const;

// 语言包
const translations = { en, zh };

// 获取浏览器语言
const getBrowserLanguage = (): 'en' | 'zh' => {
  return 'zh';
};

// 创建语言状态
export const currentLanguage = writable<'en' | 'zh'>(
  localStorage.getItem('language') as 'en' | 'zh' || getBrowserLanguage()
);

// 监听语言变化并保存
currentLanguage.subscribe((lang) => {
  localStorage.setItem('language', lang);
});

// 创建翻译函数
export const t = derived(currentLanguage, ($lang) => {
  return (key: string, params?: Record<string, any>) => {
    const keys = key.split('.');
    let value = translations[$lang];
    
    for (const k of keys) {
      value = value?.[k];
    }
    
    if (typeof value === 'string' && params) {
      // 替换所有 {paramName} 形式的占位符
      return value.replace(/\{(\w+)\}/g, (match, key) => {
        return params[key]?.toString() ?? match;
      });
    }
    
    return value || key;
  };
}); 